<?php
/*
 * @Author: your name
 * @Date: 2021-11-04 09:30:41
 * @LastEditTime: 2022-02-21 16:35:16
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \property\app\Http\Common\common.php
 */

if (!function_exists('toJson')) {

    /**
     * @description: 信息返回
     * @param {*} $code      状态码
     * @param {*} $msg       信息
     * @param {*} $data      数组
     * @param {*} $trueCode  真实http状态码
     * @param {*} $error     错误信息
     * @return {*}
     */
    function toJson($code = 200, $msg = '', $data = [], $trueCode = 200 , $error = false)
    {
        // $debug = config('debug');
        $res = [
            'code' => $code,
            'message' => $msg,
            'data' => $data,
        ];
        // var_dump( config('app.debug') );
        if ($error && config('app.debug') == false) {     // 产生HTTP错误错误 并且是线上环境不开启错误信息  
            swooleWriteLogFunc(['request' => $_POST['REQUEST_ALL'], 'response' => $res]);//这里提前写入错误日志
            $res['error'] = true;     //错误将在这里提前写入外面就不写
           
           if($res['code'] == 500 ){
                $res['message'] = '';
           }
        }
        $result =  json_encode($res, JSON_UNESCAPED_UNICODE);
        $_POST['HTTP_SERVER']->status($trueCode);
         

        return response($result);
    }
}
if (!function_exists('missingParameter')) {
    function  missingParameter()
    {
        // toJson(400, '缺少参数');
        abort(400);
    }
}



if (!function_exists('create_uuid')) {
    /**
     * @description: 生成唯一uuid
     * @param  string $prefix   前缀
     * @return string
     */
    function create_uuid($prefix = "")
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr($chars, 0, 8) . '-'
            . substr($chars, 8, 4) . '-'
            . substr($chars, 12, 4) . '-'
            . substr($chars, 16, 4) . '-'
            . substr($chars, 20, 12);
        return $prefix . $uuid;
    }
}

if (!function_exists('filtrfunction')) {
    /**
     * @description: 过滤
     */
    function  filtrfunction($arr)
    {
        if ($arr === '' || $arr === null) {
            return false;
        }
        return true;
    }
}

if (!function_exists('havaWhereLikeJoinEqual')) {
    /**
     * @description:  WHERE LIKE 条件
     * @param  array         $keyWord
     * @param  bool          $check   true时开头加AND
     * @param  bool          $last    true时为结尾不含AND false有and
     * @param  bool          $jian    剪开
     * @return string $keystr  拼接
     */
    function havaWhereLikeJoinEqual($keyWord, $check = true, $last = true, $jian = '-', $pre = "AND")
    {
        $keystr = ($check ? ' ' . $pre . ' ' : ' ');
        foreach ($keyWord as $keys => $val) {
            list($op, $joinStr, $key) = explode($jian, $keys);
            $keystr .=  ' `' . $joinStr . '`.`' . $key . '`  ' . mysql_symbol($op, $val);
            $keystr .=  ' ' . $pre;
        }
        if ($last) {
            return substr($keystr, 0,  -strlen($pre));
        } else {
            return $keystr;
        }
    }
}


if (!function_exists('havaWhereLikeManyField')) {
    /**
     * @description:         一个本文搜多个字段
     * @param  array         $manyField    ['whereConfig'=>'AND','whereField'=>[    'like-tableName-field'=> [value => 222 , whereConfig=>'AND' ],   ] ]
     * @return string $keystr  拼接
     * @return string $jian    剪切符号
     * @return bool   $needHeader   true为开头需要 AND false 为不需要
     */
    function havaWhereLikeManyField($manyField, $jian = '-', $needHeader = true)
    {
        $keyStr = '';
        $headerStrlen = 0;
        for ($i = 0; $i < count($manyField); $i++) {
            $preStr  = $manyField[$i]['whereConfig'] ?? 'AND';
            $keyStr .= ' ' . $preStr;
            if ($i == 0) {
                $headerStrlen = mb_strlen($keyStr);
            }
            $keyStr .= ' ( ';
            $priority =  $manyField[$i]['whereField'] ?? $manyField[$i];
            $twoStr = '';
            foreach ($priority as $key => $val) {
                $preTwo = $val['whereConfig'] ?? 'OR';
                $value  = $val['value'] ?? $val;
                list($op, $joinStr, $key) = explode($jian, $key);
                $twoStr .=  ' `' . $joinStr . '`.`' . $key . '`  ' . mysql_symbol($op, $value);
                $twoStr .=  ' ' . $preTwo;
            }
            $twoStr = substr($twoStr, 0,  -strlen($preTwo));
            $keyStr .=   $twoStr . ' ) ';
        }
        return   $needHeader ? $keyStr : substr($keyStr, $headerStrlen);
    }
}



if (!function_exists('mysql_or_and')) {

    //    $keyWord =  [
    //         'AND' => [
    //                 'OR' =>  [
    //                            ['like-building-address'=>"1",'like-building-title'=>"1" ], 
    //                       ]
    //                 ]
    //         ];
    /**
     * @description: 拼接or and
     * @param  array  $keyWord  上面为keyWord类型
     * @return string $keyStr
     */
    function mysql_or_and($keyWord  = [])
    {
        $keyStr = '';
        foreach ($keyWord as $key => $val) {
            foreach ($val as $keys => $vals) {
                for ($i = 0; $i < count($vals); $i++) {
                    $tmp = array_filter($vals[$i], 'filtrfunction');
                    if (!empty($tmp)) {
                        $keyStr .=   $key . ' ( ' . havaWhereLikeJoinEqual($tmp, false, true, "-", $keys) . ' ) ';
                    }
                }
            }
        }
        return    $keyStr;
    }
}




if (!function_exists('mysql_symbol')) {

    /**
     * @description: mysql符号
     * @param  string $op   操作
     * @param  string $val  值
     * @return string
     */
    function mysql_symbol($op, $val)
    {
        switch ($op) {
            case 'like':
                return ' LIKE  "%' . $val . '%" ';
            case 'greaterEq':
                return ' >= "' . $val . '" ';
            case 'lessEq':
                return ' <= "' . $val . '" ';
            case 'between':
                list($left, $right) =  explode(',', $val);
                return ' between ' . $left . ' AND  ' . $right . ' ';
            case 'equal':
                return ' = "' . $val . '" ';
            case 'notIn':
                return ' NOT  IN  (' . $val . ') ';
            case 'in':
                return '   IN  (' . $val . ') ';
            default:
                return ' = "' . $val . '" ';
        }
    }
}





if (!function_exists('limit_joint')) {

    /**
     * @description: limit 拼接
     * @param  int $page  第几页
     * @param  int $limit 一页显示几条
     * @return string
     */
    function limit_joint($page, $limit)
    {
        return ' LIMIT  ' . ($page - 1) * $limit . ',' . $limit;
    }
}

if (!function_exists('fileUnlink')) {

    /**
     * @description:  判断文件是否存在存在就删除
     * @param  string   $path  文件路径
     * @return bool     true为删除成功  false删除失败
     */
    function fileUnlink($path)
    {
        if (file_exists($path)) {
            return   unlink($path); //判断文件时否存在，存在就删除
        }
    }
}



if (!function_exists('hMgetToArray')) {

    /**
     * @description: hMget转键值数组
     * @param {*}
     * @return {*}
     */
    function hMgetToArray($hMget, $field)
    {
        $data = [];
        for ($i = 0; $i < count($hMget); $i++) {
            $data[$field[$i]] = $hMget[$i];
        }
        return  $data;
    }
}


if (!function_exists('insertUpdatedStr')) {
    /**
     * @description: 插入更新语句转化字符串
     * @param  array $array  表单数据
     * @return array
     */
    function insertUpdatedStr($array)
    {
        $data = [];
        $keyStr = '';
        $valStr = '';
        $updateStr = '';
        foreach ($array as $key => $val) {
            $keyStr .= '`' . $key . '`,';
            $valStr .= '"' . $val . '",';
            $updateStr .= '`' . $key . '`= "' . $val . '",';
        }
        $keyStr = substr($keyStr, 0, -1);
        $valStr = substr($valStr, 0, -1);
        $updateStr = substr($updateStr, 0, -1);
        $data['keyStr'] = $keyStr;
        $data['valStr'] = $valStr;
        $data['updateStr'] = $updateStr;
        return  $data;
    }
}


if (!function_exists("http_request")) {

    /**
     * @description:  curl 请求
     * @param    string   $url     请求地址
     * @param    mixed    $data     转成json数据发送参数
     * @return   mixed    $output
     */
    function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        //var_dump(curl_error($curl));
        curl_close($curl);
        return $output;
    }
}
